/************************************************************
 * Project Name         [Thinking_In_Java]
 * File Name            [Example_01_Store_Object_As_Text.java]
 * Creation Date        [06-Jul-2014]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ************************************************************/
package pkg_09_io.basic;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Scanner;

/**
 * 测试文本输入/输出(以文本的方式存储对象)
 * 
 * @author 不落的太阳(Sean Yang)
 * @version 1.0
 * @since JDK 6
 * 
 */
public class Example_01_Store_Object_As_Text {

	/**
	 * 写出数据
	 * 
	 * @param out
	 * @param employee
	 */
	private void writeData(PrintWriter out, Employee employee) {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(employee.getHireDate());
		out.println(employee.getName() + "|" + employee.getSalary() + "|"
				+ calendar.get(Calendar.YEAR) + "|"
				+ (calendar.get(Calendar.MONTH) + 1) + "|"
				+ calendar.get(Calendar.DAY_OF_MONTH));
	}

	/**
	 * 读入数据
	 * 
	 * @param scanner
	 */
	private void readData(Scanner scanner) {
		String line = scanner.nextLine();
		String[] tokens = line.split("\\|");
		Employee employee = new Employee(tokens[0],
				Double.parseDouble(tokens[1]), Integer.parseInt(tokens[2]),
				Integer.parseInt(tokens[3]), Integer.parseInt(tokens[4]));
		System.out.println(employee);
	}

	/**
	 * 将每一个员工信息输出到文件
	 * 
	 * @param employees
	 * @param out
	 * @throws IOException
	 */
	public void write(PrintWriter out, Employee[] employees) throws IOException {
		out.println("Employee numbers : " + employees.length);
		for (Employee employee : employees) {
			writeData(out, employee);
		}
	}

	/**
	 * 从文件读入每一个员工信息
	 * 
	 * @param scanner
	 * @throws IOException
	 */
	public void read(Scanner scanner) throws IOException {
		String info = scanner.nextLine();
		System.out.println(info);

		while (scanner.hasNext()) {
			readData(scanner);
		}
	}

	/**
	 * 测试方法
	 * 
	 * @param args
	 *            命令行参数
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public static void main(String[] args) throws FileNotFoundException,
			IOException {
		Employee[] employees = new Employee[3];
		employees[0] = new Employee("Sean", 100000, 1984, 3, 24);
		employees[1] = new Employee("CC", 100000, 1985, 4, 24);
		employees[2] = new Employee("Yang", 100000, 1986, 5, 24);

		Example_01_Store_Object_As_Text test = new Example_01_Store_Object_As_Text();

		PrintWriter out = new PrintWriter("employee.txt");
		test.write(out, employees);
		out.close();

		Scanner scanner = new Scanner(new FileReader("employee.txt"));
		test.read(scanner);
		scanner.close();

	}

}
